<?php
echo CHtml::script("var currentProductId=0;
					var currentOrderFirmId=0;
	    function messagebox(message,iserror){
			$('#messagebox').html(message);
			if(iserror) $('#messagebox').css('color','red'); else $('#messagebox').css('color','green');
	        $('#messagebox').fadeTo(\"slow\", 1).animate({opacity: 1.0}, 3000).fadeTo(\"slow\", 0);
	    }");
Yii::app()->clientScript->registerScript("fadingElements",
"$('#currentbillmessage').fadeTo(0, 0);
$('#currentordermessage').fadeTo(0, 0);
");

$this->breadcrumbs=array(
	'Products',
);

$this->menu=array(
	array('label'=>'Створити продукт', 'url'=>array('create')),
	array('label'=>'Створити фірму', 'url'=>array('/firms/create')),
	array('label'=>'Створити накладну', 'url'=>array('/bills/create')),
	array('label'=>'Створити замовлення', 'url'=>array('/orders/create')),
);

$selectBillFunction = <<<TMP
function(id){
		var selections = $.fn.yiiGridView.getSelection(id);
		var billid = selections[0];
		var rows=$.fn.yiiGridView.getSelectedRows(id);
		var billname = rows[0][0].innerHTML;
		var bid = $('#billidElement');
		var bname = $('#billnameElement');
		bid.val(billid);
		bname.text(billname);
		var ajaxUrl = '/index.php?r=products/processbill&action=change&id='+billid;
		jQuery.ajax({'url':ajaxUrl,'cache':false,'success':function(data){document.getElementById('currentbill').innerHTML=data;}}); 
		$('#billsdialog').dialog("close");
		return false;
	}
TMP;

$selectOrderFunction = <<<TMP
function(id){
		var selections = $.fn.yiiGridView.getSelection(id);
		var orderid = selections[0];
		var rows=$.fn.yiiGridView.getSelectedRows(id);
		var ordername = rows[0][0].innerHTML;
		var oid = $('#orderidElement');
		var oname = $('#ordernameElement');
		oid.val(orderid);
		oname.text(ordername);
		var ajaxUrl = '/index.php?r=products/processorder&action=change&id='+orderid;
		jQuery.ajax({'url':ajaxUrl,'cache':false,'success':function(data){document.getElementById('currentorder').innerHTML=data;}}); 
		$('#ordersdialog').dialog("close");
		$.fn.yiiGridView.update("yw4");
		return false;
	}
TMP;

echo CHtml::script('
function preparedel(id,name){
	document.getElementById("delproductid").value = id;
	document.getElementById("delproductname").innerHTML = name;
	$("#delproddialog").dialog("open"); 
	return false;
}');
?>

<h1>Магазин</h1>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'billsdialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'bills',
        'autoOpen'=>false,
		'width'=>600
    ),
));

$this->widget('zii.widgets.grid.CGridView', array(
	'dataProvider'=>$billsmodel->search(),
	'columns'=>array(
		array(
			'value'=>'$data->name',
			'header'=>'Накладна',
			'name'=>'name'
		),
		array(
			'value'=>'$data->supplier->name',
			'header'=>'Постачальник',
			'name'=>'supplierid',
			'filter'=>CHtml::dropDownList("Bills[supplierid]",$billsmodel->supplierid,$dataForSuppliersDropdown)
		),
		array(
			'value'=>'$data->created',
			'header'=>'Створено',
			'name'=>'created'
		),
		array(
			'value'=>'Bills::getPaidStatusText($data->paid)',
			'header'=>'Оплачено',
			'name'=>'paid',
			'filter'=>CHtml::dropDownList("Bills[paid]",$billsmodel->paid,array("-1"=>Bills::getPaidStatusText(),"0"=>Bills::getPaidStatusText(0),"1"=>Bills::getPaidStatusText(1)))
		),
	),
	'filterPosition'=>'body',
	'filter'=>$billsmodel,
	'selectableRows'=>1,
	'selectionChanged'=>$selectBillFunction,
));
$this->endWidget('zii.widgets.jui.CJuiDialog');


$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'ordersdialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'orders',
        'autoOpen'=>false,
		'width'=>600
    ),
));
$this->widget('zii.widgets.grid.CGridView', array(
	'dataProvider'=>$ordersmodel->search(),
	'columns'=>array(
		array(
			'value'=>'$data->name',
			'header'=>'Замовлення',
			'name'=>'name'
		),
		array(
			'value'=>'$data->firmid',
			'header'=>'Фірма',
			'name'=>'firmid',
			'filter'=>CHtml::dropDownList("Orders[firmid]",$ordersmodel->firmid,$dataForFirmsDropdown)
		),
		array(
			'value'=>'$data->created',
			'header'=>'Створено',
			'name'=>'created'
		),
	),
	'filterPosition'=>'body',
	'filter'=>$ordersmodel,
	'selectableRows'=>1,
	'selectionChanged'=>$selectOrderFunction,
));
$this->endWidget('zii.widgets.jui.CJuiDialog');

$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'addproddialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'Додати',
        'autoOpen'=>false,
		'width'=>600
    ),
));
echo CHtml::beginForm();
echo CHtml::tag('div',array('id'=>'addprodcontrol'),"&nbsp;");
echo CHtml::ajaxSubmitButton('Save',CHtml::normalizeUrl(array('store/create')),array('success'=>'js: function(data) {var row=$.fn.yiiGridView.getRowByKey("yw4",currentProductId);row[3].innerHTML=parseInt(row[3].innerHTML)+parseInt(document.getElementById("count").value);$("#addproddialog").dialog("close");}'),array('id'=>'addproductbutton','name'=>'addproductbutton'));
echo CHtml::button('Close',array('onclick'=>'$(\'#addproddialog\').dialog("close")'));
echo CHtml::endForm();
$this->endWidget('zii.widgets.jui.CJuiDialog');

$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'sellproddialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'Sell product',
        'autoOpen'=>false,
		'width'=>600
    ),
));
echo CHtml::beginForm();
echo CHtml::tag('div',array('id'=>'sellprodcontrol'),"&nbsp;");
echo CHtml::ajaxSubmitButton('Sell',CHtml::normalizeUrl(array('store/update')),array('success'=>'js: function(data) {var row=$.fn.yiiGridView.getRowByKey("yw4",currentProductId);var cnt=parseInt(row[3].innerHTML)-parseInt(document.getElementById("selcount").value);if(cnt<0) cnt=0;row[3].innerHTML=cnt;$("#sellproddialog").dialog("close");}'),array('id'=>'sellproductbutton','name'=>'sellproductbutton'));
echo CHtml::button('Close',array('onclick'=>'$(\'#sellproddialog\').dialog("close")'));
echo CHtml::endForm();
$this->endWidget('zii.widgets.jui.CJuiDialog');


$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'addtoorderdialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'Add to order',
        'autoOpen'=>false,
		'width'=>600
    ),
));
echo CHtml::beginForm();
echo CHtml::tag('div',array('id'=>'ordercontrol'),"&nbsp;");
echo CHtml::ajaxSubmitButton('Add to order',CHtml::normalizeUrl(array('products/addtoorder')),array('success'=>'js: function(data) {$("#addtoorderdialog").dialog("close");}'),array('id'=>'addtoorderbutton','name'=>'addtoorderbutton'));
echo CHtml::button('Close',array('onclick'=>'$(\'#addtoorderdialog\').dialog("close")'));
echo CHtml::endForm();
$this->endWidget('zii.widgets.jui.CJuiDialog');

$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
    'id'=>'delproddialog',
    // additional javascript options for the dialog plugin
    'options'=>array(
        'title'=>'Delete product',
        'autoOpen'=>false,
		'width'=>600
    ),
));
echo CHtml::beginForm();
?>
<table>
	<tr><td>Product:</td><td id="delproductname"></td></tr>
	<tr><td>Count:</td><td><?php echo CHtml::textField("delcount",1,array("id"=>"delcount")); ?></td></tr>
</table>
<?php
echo CHtml::hiddenField("delproductid",0,array("id"=>"delproductid"));
echo CHtml::ajaxSubmitButton('Delete',CHtml::normalizeUrl(array('store/delete',"ajax"=>1)),array('success'=>'js: function(data) 
	{
		var row=$.fn.yiiGridView.getRowByKey("yw4",currentProductId);
		var cnt=parseInt(row[3].innerHTML)-parseInt(document.getElementById("delcount").value);
		if(cnt<0) cnt=0; 
		row[3].innerHTML=cnt;
		$("#delproddialog").dialog("close");
	}'),array('id'=>'delproductbutton','name'=>'delproductbutton'));
echo CHtml::button('Close',array('onclick'=>'$(\'#delproddialog\').dialog("close")'));
echo CHtml::endForm();
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
<div id="block2">

<fieldset id="currentbillfieldset">
<legend>Поточна накладна</legend>
<?php	echo Chtml::beginForm(Chtml::normalizeUrl(array('bills/pay')));?>
<div id="currentbill" class="controlsblock">
<?php
$this->renderPartial("currentbill",array("billid"=>$billid,"billname"=>$billname));
?>
</div>
<?php
	echo Chtml::ajaxSubmitButton("Оплата",Chtml::normalizeUrl(array('bills/pay')),array("success"=>"function(data){if(data=='OK') messagebox('Успішно',false); else messagebox(data,true); $('#billpay').val(0);}"));
	echo Chtml::endForm(); 
?>
</fieldset>



<fieldset id="currentorderfieldset">
<legend>Поточне замовлення</legend>
<?php echo Chtml::beginForm(Chtml::normalizeUrl(array('orders/pay')));?>
<div id="currentorder" class="controlsblock">
<?php
$this->renderPartial("currentorder",array("orderid"=>$orderid,"ordername"=>$ordername));
?>
</div>
<?php
	echo Chtml::ajaxSubmitButton("Оплата",Chtml::normalizeUrl(array('orders/pay')),array("success"=>"function(data){if(data=='OK') messagebox('Успішно',false); else messagebox(data,true); $('#orderpay').val(0);$('#returned').attr('checked',false);}"));
	echo Chtml::checkBox("returned",false,array("id"=>"returned"))."&nbsp;Пов.";
	echo Chtml::endForm();
?>
</fieldset>

</div>
<div id="block1">
<fieldset id="currentdatefieldset">
<legend>Поточна дата</legend>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'publishDate',
    // additional javascript options for the date picker plugin
    'options'=>"js:{onSelect:function(dateText,inst){var ajaxUrl = '/index.php?r=site/session&key=currentdate&value='+dateText;jQuery.ajax({'url':ajaxUrl,'cache':false});},'showAnim':'fold','dateFormat':'yy-mm-dd'}",
    'htmlOptions'=>array(
        'style'=>'height:20px;',
		'id'=>'publishDate',
		'class'=>'controlsblock'
    ),
	'value'=>$datebuy
));
?>
</fieldset>
<div id="incomes" class="controlsblock">
<fieldset>
<legend>Доход</legend>
	<?php echo Chtml::beginForm(Chtml::normalizeUrl(array('otherincomes/pay'))); 
	echo CHtml::dropDownList("Otherincomes[income]",null,$dataForIncomesDropdown);
	echo Chtml::textField('Otherincomes[sum]',0,array('id'=>'otherincomesum',"style"=>"width:30px;")); 
	echo Chtml::ajaxSubmitButton("Оплата",Chtml::normalizeUrl(array('otherincome/pay')),array("success"=>"function(data){if(data=='OK') messagebox('Успішно',false); else messagebox(data,true); $('#otherincomesum').val(0);}"));
	echo Chtml::endForm(); ?>
</legend>
</div>
<div id="outcomes" class="controlsblock">
<fieldset>
<legend>Виплати</legend>
<?php echo Chtml::beginForm(Chtml::normalizeUrl(array('otheroutcomes/pay'))); 
	echo CHtml::dropDownList("Otheroutcomes[outcome]",null,$dataForOutcomesDropdown);
	echo Chtml::textField('Otheroutcomes[sum]',0,array('id'=>'otheroutcomesum',"style"=>"width:30px;")); 
	echo Chtml::ajaxSubmitButton("Оплата",Chtml::normalizeUrl(array('otheroutcome/pay')),array("success"=>"function(data){if(data=='OK') messagebox('Успішно',false); else messagebox(data,true); $('#otheroutcomesum').val(0);}"));
	echo Chtml::endForm(); ?>
</fieldset>
</div>
</div>

<div id="messagebox"></div>
<?php 
//$orderfirmid = Yii::app()->session->get("orderfirmid",0);

$this->widget('zii.widgets.grid.CGridView', array(
	'dataProvider'=>$model->search(),
	'columns'=>array(
		array(
			'value'=>'$data->name',
			'header'=>'Продукт',
			'name'=>'name'
		),
		array(
			'value'=>'$data->firm->name',
			'header'=>'Фірма',
			'name'=>'firmid',
			'filter'=>CHtml::dropDownList("Products[firmid]",$model->firmid,$dataForFirmsDropdown)
		),
		array(
			'value'=>'$data->price',
			'header'=>'Ціна',
			'name'=>'price'
		),
		array(
			'value'=>'$data->unsoldcount',
			'header'=>'Кількість',
			'name'=>'unsoldcount',
		),
		array(
			'value'=>'$data->isactive',
			'header'=>'Активний',
			'name'=>'isactive',
		),
		array(
			'value'=>'CHtml::link(CHtml::image("images/editIcon.gif"),CHtml::normalizeUrl(array("products/update","id"=>$data->id)))',
			'type'=>'raw'
		),
		array(
			'value'=>'CHtml::link(CHtml::image("images/plus16x16.png"),"",array("onclick"=>CHtml::ajax(array(
												"url"=>CHtml::normalizeUrl(array("ajax","id"=>$data->id)),
												"success"=>"function(data,textStatus,jqXHR){currentProductId=".$data->id.";document.getElementById(\"addprodcontrol\").innerHTML=data;\$(\"#addproddialog\").dialog(\"open\"); return false;}")
												)))',
			'type'=>'raw'
		),
		array(
			'value'=>'CHtml::link(CHtml::image("images/dollar16x16.png"),"",array("onclick"=>CHtml::ajax(array(
												"url"=>CHtml::normalizeUrl(array("ajaxsell","id"=>$data->id)),
												"success"=>"function(data,textStatus,jqXHR){currentProductId=".$data->id.";document.getElementById(\"sellprodcontrol\").innerHTML=data;\$(\"#sellproddialog\").dialog(\"open\"); return false;}")
												)))',												
			'type'=>'raw'
		),
		array(
			'value'=>'(Yii::app()->session->get("orderfirmid",0)==$data->firmid) ?
			CHtml::link(CHtml::image("images/list.png"),"",array("onclick"=>CHtml::ajax(array(
												"url"=>CHtml::normalizeUrl(array("ajaxorder","id"=>$data->id)),
												"success"=>"function(data,textStatus,jqXHR){currentProductId=$data->id;document.getElementById(\'ordercontrol\').innerHTML=data;\$(\"#addtoorderdialog\").dialog(\"open\"); return false;}")
												))):CHtml::image("images/listgrey.png")',
			'type'=>'raw'
		),
		array(
			'value'=>'CHtml::link(CHtml::image("images/minus16x16.png"),array("#"),array("onclick"=>"currentProductId=$data->id;preparedel($data->id,\"".addslashes($data->name)."\");\$(\"#delproddialog\").dialog(\"open\");return false;"))',
			'type'=>'raw'
		),
	),
	'filterPosition'=>'body',
	'filter'=>$model
)); 

//echo CHtml::script("jQuery('#publishDate').datepicker({onSelect: function(dateText, inst) { var ajaxUrl = '/index.php?r=site/session&key=datebuy&value='+dateText;jQuery.ajax({'url':ajaxUrl,'cache':false});  }})");
?>